function formatTime(date) {
    var year = date.getFullYear()
    var month = date.getMonth() + 1
    var day = date.getDate()

    var hour = date.getHours()
    var minute = date.getMinutes()
    var second = date.getSeconds()


    return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function formatNumber(n) {
    n = n.toString()
    return n[1] ? n : '0' + n
}


function httpRequest(obj, shouldAcceptSessionCookie, httpReqDeep) {
    var acceptSessionCookie = (shouldAcceptSessionCookie!==false)
    // add cookie to request header.
    var sessionId = wx.getStorageSync('PHPSESSID')
    if (sessionId) {
        if (obj.header===undefined) {
            obj.header = {}
        }
        obj.header['cookie'] = 'PHPSESSID=' + sessionId + ';'
    }

    obj.url = makeUrl(obj.url)
    
    // console.log(httpReqDeep);
    if(httpReqDeep===undefined){
        httpReqDeep=1
    }else if(httpReqDeep>3){
        console.log('tried 3 times before failed. maybe server error');
        return
    }

    if (acceptSessionCookie) {
        var userSuccessFunc
        if (obj.success) {
            userSuccessFunc = obj.success
        } else {
            userSuccessFunc = function () { }
        }

        obj.success = function (res) {
            var cookie = res.header['Set-Cookie'];
            if (cookie) {
                //console.log(cookie)
                if (Array.isArray(cookie)) {
                    for (var i in cookie) {
                        var match = cookie[i].match(/PHPSESSID=([^;]+);/)
                        if (match) {
                            var sessionId = match[1]
                            wx.setStorageSync('PHPSESSID', sessionId)
                            break;
                        }
                    }
                } else {
                    var match = cookie.match(/PHPSESSID=([^;]+);/)
                    if (match) {
                        var sessionId = match[1]
                        wx.setStorageSync('PHPSESSID', sessionId)
                    }
                }
            }
            if (res.data.error && res.data.error =='login required'){
                console.log('need login')
                wx.login({
                    success: function (res) {
                        if (res.code) {
                            // console.log(res.code)
                            httpRequest({
                                url: '/User/login',
                                method: 'GET',
                                data: {
                                    code: res.code
                                },
                                success: function (res) {
                                    console.log('login success')
                                    wx.setStorageSync('unlockDesp', res.data.unlockDesp)
                                    obj.success = userSuccessFunc
                                    console.log(obj)
                                    httpRequest(obj, false)
                                },
                                fail: function(res){
                                    console.log(res)
                                }
                            }, true, httpReqDeep+1);
                        } else {
                            console.log('获取用户登录态失败！' + res.errMsg)
                        }
                    },
                    fail: function (res) {
                        console.log('获取用户登录态失败！' + res.errMsg)
                    }
                }) //重新登录
            }else{
                userSuccessFunc(res)
            }
        }
        // obj.complete = function (res) {
        //     //if(res.errorMsg) 
        //     console.log(res)
        // }
    }

    wx.request(obj)
}


function downloadAndOpen(url) {
    wx.showLoading({
        title: '加载中',
        mask: true,
        complete:function(){
            wx.downloadFile({
                url: url,
                success: function (res) {
                    wx.hideLoading()
                    console.log(res)
                    var filePath = res.tempFilePath
                    wx.openDocument({
                        filePath: filePath,
                        success: function (res) {
                            console.log('打开文档成功')
                        }
                    })
                }
            })
        }
    })
}

function makeUrl(path){
    if (path.startsWith('/')){
        return 'https://www.water-crystal.org/WechatApp' + path;
    }else{
        return path;
    }
}

module.exports = {
    formatTime: formatTime,
    httpRequest: httpRequest,
    downloadAndOpen: downloadAndOpen,
    url: makeUrl
}
